import { FBaseAd } from "../../core/ad/FBaseAd";
import { FIRewardAd } from "../../core/ad/FIRewardAd";
import { FResultFunc, FResultState, FSDKState } from "../../init";

export class FWXRewardAd extends FBaseAd implements FIRewardAd {

    protected rewardAd: any;


    protected callback: FResultFunc;
    setResultFunc(func: FResultFunc): void {
        this.callback = func;
    }

    load() {
        if (this.rewardAd) {
            this.rewardAd.load();
        }
    }

    open(): void {
        this.destroy();
        this.create();
    }


    show() {
        if (this.rewardAd) {
            this.rewardAd.show().then(() => {
            }).catch(() => {
                this.onError('show error ')
            })
        } else {
            this.onError('this.rewardAd is null')
        }
    }

    onLoad() {
        this.show();
    }

    onError(err: any) {
        console.log(' 视频播放失败 ', err)
        if (this.callback) {
            this.callback(FResultState.NO);
            this.callback = null;
        }
    }

    onClose(res: any) {
        if (res && res.isEnded || res === undefined) {
            // console.log('视频结束关闭 ')
            // 正常播放结束，可以下发游戏奖励
            if (this.callback) {
                this.callback(FResultState.YES)
                this.callback = null;
            }

        } else {
            // 播放中途退出，不下发游戏奖励
            // console.log('视频中途关闭 ')
            if (this.callback) {
                this.callback(FResultState.NO);
                this.callback = null;
            }

        }
    }

    create(): void {
        if (!this.rewardAd) {
            // console.log(' 不支持多例')
            this.rewardAd = this.sdk.createRewardedVideoAd({ adUnitId: this.id })
            this.rewardAd.onLoad(this.getFunc(this.onLoad))
            this.rewardAd.onError(this.getFunc(this.onError))
            this.rewardAd.onClose(this.getFunc(this.onClose))
        } else {
            //微信会在第一次创建的时候默认load一次。
            this.rewardAd.load();
        }

    }

    destroy(): void {
        if (this.rewardAd) {
            this.rewardAd.offLoad(this.getFunc(this.onLoad))
            this.rewardAd.offError(this.getFunc(this.onError))
            this.rewardAd.offClose(this.getFunc(this.onClose))
            this.rewardAd.destroy();
            this.rewardAd = null;
        }
    }
}